﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace PrintConverter
{
    public class MainWindowViewModule
    {
        private readonly MainWindow _window;
        private readonly Module _module;
        private readonly Command _optionChangedCommand;
        private readonly Command _valueChangedCommand;
        private readonly Command _dpiChangedCommand;

        public MainWindowViewModule(MainWindow window)
        {
            _window = window;
            _module = new Module();
            _optionChangedCommand = new Command(OptionChanged);
            _valueChangedCommand = new Command(ValueChanged);
            _dpiChangedCommand = new Command(DpiChanged);
            _window.DataContext = this;
        }

        public Module Module => _module;
        public ICommand OptionChangedCommand => _optionChangedCommand;
        public ICommand ValueChangedCommand => _valueChangedCommand;
        public ICommand DpiChangedCommand => _dpiChangedCommand;

        private void OptionChanged(object parameter)
        {
        }


        private void DpiChanged(object parameter)
        {
            ValueChanged(parameter);
        }

        private void ValueChanged(object paramter)
        {
            try
            {
                int dpi = 0;

                if (Module.IsHorizontal && Module.DpiX.HasValue)
                {
                    dpi = Module.DpiX.Value;
                }
                else if (Module.IsVertical && Module.DpiY.HasValue)
                {
                    dpi = Module.DpiY.Value;
                }

                if (dpi > 0)
                {
                    if (Module.IsMM && Module.MM.HasValue)
                    {
                        Module.Inch = (int)(Math.Round((float)Module.MM * (float)1000 / (float)254));
                        Module.Point = (int)((float)Module.Inch * (float)dpi / (float)100);
                    }
                    else if (Module.IsInch && Module.Inch.HasValue)
                    {
                        Module.MM = (int)(Math.Round((float)Module.Inch * 254 / 1000));
                        Module.Point = (int)(Math.Round((float)Module.Inch * (float)dpi / (float)100));
                    }
                    else if (Module.IsPoint && Module.Point.HasValue)
                    {
                        Module.Inch = (int)Math.Round((float)Module.Point * 100 / dpi);
                        Module.MM = (int)(Math.Round((float)Module.Inch * 254 / 1000));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
